﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoStar.Common
{
    public class LogHelper
    {
        private string _logFilePath;
        public LogHelper(string logFileName)
        {
            _logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs", logFileName);
            CheckLogFile();

        }
        private void CheckLogFile()
        {
            string logDirectory = Path.GetDirectoryName(_logFilePath);
            if (!Directory.Exists(logDirectory))
                Directory.CreateDirectory(logDirectory);

            if (!File.Exists(_logFilePath))
                File.Create(_logFilePath).Dispose();
        }
        public void WriteLog(string message)
        {
            //using (StreamWriter sw = new StreamWriter(_logFilePath, true))
            //{
            //    sw.WriteLine(DateTime.Now.ToString() + " " + message + "\r\n");
            //}
            bool success = false;
            int retryCount = 0;
            while (!success && retryCount < 5)
            {
                try
                {
                    using (StreamWriter sw = new StreamWriter(_logFilePath, true))
                    {
                        sw.WriteLine(DateTime.Now.ToString() + " " + message + "\r\n");
                        success = true; // 如果没有异常，设置成功标志
                    }
                }
                catch (IOException ex)
                {
                    retryCount++;
                    if (retryCount < 5)
                    {
                        Thread.Sleep(100); // 等待一段时间后重试
                    }
                    else
                    {
                        // 记录错误信息或采取其他行动
                        Console.WriteLine("无法写入日志文件: " + ex.Message);
                    }
                }
            }
        }
    }
}
